import QRCode from 'qrcode'

export interface TraceabilityData {
  commodityId: number
  commodityName: string
  batchNumber: string
  manufacturer: string
  productionLicense: string
  shelfLifeDays: number
  createTime: string
  traceabilityUrl: string
}

function getBaseUrl(): string {
  // 优先使用环境变量 VITE_QR_BASE_URL，否则用 window.location.origin
  // @ts-ignore
  const envBaseUrl = import.meta.env.VITE_QR_BASE_URL
  if (envBaseUrl && typeof envBaseUrl === 'string' && envBaseUrl.startsWith('http')) {
    return envBaseUrl.replace(/\/$/, '')
  }
  return window.location.origin
}

export class QRCodeGenerator {
  static async generateTraceabilityQRCode(
    data: TraceabilityData,
    options: {
      size?: number
      margin?: number
      color?: {
        dark?: string
        light?: string
      }
      format?: 'PNG' | 'JPG' | 'SVG'
    } = {}
  ): Promise<string> {
    const {
      size = 300,
      margin = 2,
      color = { dark: '#000000', light: '#FFFFFF' },
      format = 'PNG'
    } = options
    const traceabilityUrl = this.buildTraceabilityUrl(data)
    const qrCodeDataUrl = await QRCode.toDataURL(traceabilityUrl, {
      width: size,
      margin: margin,
      color: color,
      type: 'image/png'
    })
    return qrCodeDataUrl
  }

  static buildTraceabilityUrl(data: TraceabilityData): string {
    const baseUrl = getBaseUrl()
    const params = new URLSearchParams({
      id: data.commodityId.toString(),
      name: encodeURIComponent(data.commodityName),
      batch: data.batchNumber,
      manufacturer: encodeURIComponent(data.manufacturer),
      license: data.productionLicense,
      shelfLife: data.shelfLifeDays.toString(),
      createTime: data.createTime
    })
    return `${baseUrl}/traceability?${params.toString()}`
  }

  static async generateBatchQRCodes(
    data: TraceabilityData,
    count: number,
    options: {
      size?: number
      margin?: number
      color?: {
        dark?: string
        light?: string
      }
    } = {}
  ): Promise<string[]> {
    const qrCodes: string[] = []
    for (let i = 0; i < count; i++) {
      const qrCode = await this.generateTraceabilityQRCode(data, options)
      qrCodes.push(qrCode)
    }
    return qrCodes
  }

  static downloadQRCode(qrCodeDataUrl: string, fileName: string): void {
    const link = document.createElement('a')
    link.href = qrCodeDataUrl
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  static downloadBatchQRCodes(qrCodes: string[], baseFileName: string): void {
    qrCodes.forEach((qrCode, index) => {
      const fileName = `${baseFileName}_${index + 1}.png`
      this.downloadQRCode(qrCode, fileName)
    })
  }
} 